package com.sharkburner.aeris.service.article.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer;

import com.sharkburner.aeris.bean.article.ArticleBean;
import com.sharkburner.aeris.dao.ArticleDao;
import com.sharkburner.aeris.dao.entity.Article;
import com.sharkburner.aeris.dao.entity.ArticleState;
import com.sharkburner.aeris.dao.entity.Site;
import com.sharkburner.aeris.dao.entity.User;
import com.sharkburner.aeris.dao.entity.UserSite;
import com.sharkburner.aeris.service.article.ArticleService;
import com.sharkburner.common.dao.paginator.LazyPaginator;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    protected ArticleDao articleDao;

    @Autowired
    protected LazyPaginator paginator;

    @Override
    public List<Article> findArticles(User user, Site site) {

	return articleDao.findAll(new UserSite(user, site), new ArticleState(
		ArticleState.UNREAD));
    }

    @Override
    @Transactional
    public void save(Site site, List<ArticleBean> beans) {
	for (ArticleBean bean : beans) {
	    Article article = new Article();
	    article.setDateCreation(bean.getDateCreation());
	    article.setDescr(bean.getDescr());
	    article.setLink(bean.getLink());
	    article.setName(bean.getName());
	    article.setSite(site);

	    articleDao.save(article);
	}
    }

    @Override
    @Transactional(readOnly = false)
    public LazyQueryContainer findArticles() {
	return paginator.build(articleDao.findAll());
    }

}
